package cc.sheji.service;


import cc.sheji.domain.Device;
import cc.sheji.domain.DeviceQueryCriteria;
import cc.sheji.reposity.DeviceRepository;
import cc.sheji.util.QueryHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Service
public class DeviceService {

    @Autowired
    DeviceRepository deviceRepository;

    public Device create(Device entity) {

        entity.setId(null);
        entity=deviceRepository.save(entity);
        return entity;
    }

    public Device get(@PathVariable("id") Long id) {

        Device entity = deviceRepository.findById(id).get();
        return entity;
    }

    public List<Device> list(DeviceQueryCriteria criteria, Pageable pageable) {

        Sort order = Sort.by(Sort.Direction.DESC, "createTime");
        if (criteria.getOrderType() != null && 1 == criteria.getOrderType()) {
            order = Sort.by(Sort.Direction.ASC, "createTime");
        }
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);
        Page<Device> page = deviceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return page.getContent();
    }

    public Device update(Device entity) {

        return deviceRepository.save(entity);
    }




}
